import { login, logout, getInfo, smsLogin, record } from '@/api/login'
import { getToken, setToken, removeToken, setTenantId } from '@/utils/auth'
import { logout as oauthLogout } from '@/api/oauth2/oauth2'
import { getUnreadNotifyMessageCount } from '@/api/system/notity/message'
import { getProjectListSimple } from '@/api/system/project'
import { recordProject } from '@/api/business/project'

const user = {
    state: {
        token: getToken(),
        name: '',
        avatar: '',
        hasMsg: false,
        roles: [],
        permissions: [],
        // 默认用户展示首页
        defaultIndex: localStorage.getItem('defaultIndex') || '',
        frontConfig: {
            theme: '#3A71A8',
            sideBgTheme: '#304156',
            sideTitleBgTheme: '#bfcbd9'
        },
        // 经销商简称
        simpleName: '智慧农业系统',
        unReadCount: 0
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_HAS_MSG: (state, hasMsg) => {
            state.hasMsg = hasMsg
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_SIMPLE_NAME: (state, simpleName) => {
            state.simpleName = simpleName
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        },
        SET_DEFAULT_INDEX: (state, defaultIndex) => {
            state.defaultIndex = defaultIndex
        },
        SET_FRONT_CONFIG: (state, frontConfig) => {
            state.frontConfig = frontConfig
        },
        SET_UNREAD_COUNT: (state, unReadCount) => {
            state.unReadCount = unReadCount
        },
        SET_USER_ID: (state, userId) => {
            state.userId = userId
        }
    },

    actions: {

        // 短信登录
        smsLogin({ commit }, smsInfo) {
            return new Promise((resolve, reject) => {
                smsLogin(smsInfo).then(res => {
                    setToken(res.token)
                    commit('SET_TOKEN', res.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 登录
        Login({ commit }, userInfo) {
            console.log(userInfo)
            const username = userInfo.username.trim()
            const password = userInfo.password
            const code = userInfo.code
            const uuid = userInfo.uuid
            return new Promise((resolve, reject) => {
                login(username, password, code, uuid).then(res => {
                    setToken(res.data.accessToken)
                    commit('SET_TOKEN', res.data.accessToken)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({ commit }) {
            return new Promise((resolve, reject) => {
                // console.log('GetInfo')
                getInfo().then(async res => {

                    // console.log('项目id',res.projectId)

                    let projectList = []
                   await getProjectListSimple().then(res => {
                        projectList = res.data
                    })
                    const user = res.data.user
                    const projectId = user.projectId

                   if(res.data.project!==null){
                       const projectObj = res.data.project
                       // const sysParam = res.data.sysParam
                       // const companySimpleName = res.data.companySimpleName
                       // console.log('公司简称',companySimpleName)
                       let defaultIndex = projectObj.defaultIndex
                       if (defaultIndex == null || defaultIndex === '' || defaultIndex ===undefined) {
                           defaultIndex = 'controlLoop'
                       }
                       commit('SET_DEFAULT_INDEX', defaultIndex)
                   }

                    const avatar = user.avatar == '' ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar
                    // 验证返回的roles是否是一个非空数组
                    if (res.data.roles && res.data.roles.length > 0) {
                        commit('SET_ROLES', res.data.roles)
                        commit('SET_PERMISSIONS', res.data.permissions)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                        commit('SET_PERMISSIONS', res.data.permissions)
                    }
                    commit('SET_NAME', user.nickname)
                    commit('SET_USER_ID', user.id)
                    // console.log('上次项目', projectId)

                    commit('SET_PROJECT_ID', projectId)
                    // if(sysParam!==null){
                    //     commit('SET_SYS_PARAM',sysParam)
                    // }
                    let arr = []
                    for (let i = 0, len = projectList.length; i < len; ++i) {
                        let item = projectList[i]
                        let temp = { 'value': 0, 'label': '', 'disabled': false }
                        temp['value'] = item.id
                        temp['label'] = item.name
                        arr.push(temp)
                        if (projectId == null) {
                            if (i === 0) {
                                recordProject(item.projectId).then(response => {
                                })
                                commit('SET_PROJECT_ID', item.projectId)
                            }
                        }
                    }
                    // console.log('arr',arr)
                    commit('SET_PROJECT_LIST', arr)
                    // commit('SET_PROJECT_DATA_LIST', projectList)
                    commit('SET_AVATAR', avatar)
                    // commit('SET_COMPANY_SIMPLE_NAME',companySimpleName)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    // window.location.reload()
                    reject(error)
                })
            })
        },

        SetDefaultIndex({ commit }, defaultIndex) {
            commit('SET_DEFAULT_INDEX', defaultIndex)
        },
        SetUnReadCount({ commit }, unReadCount) {
            return new Promise((resolve, reject) => {
                getUnreadNotifyMessageCount().then((res) => {
                    commit('SET_UNREAD_COUNT', res.data)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        SetHasMsg({ commit }, projectId) {
            return new Promise(resolve => {
                console.log('SetHasMsg projectId', projectId)
                getHasMsg(projectId).then(res => {
                    let hasMsg = res.hasMsg
                    commit('SET_HAS_MSG', hasMsg)
                    resolve(hasMsg)
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user
